﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Atmk.WaterMeter.MIS.Common;
using Atmk.WaterMeter.MIS.Datas;
using Atmk.WaterMeter.MIS.Entities.Enums;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NLog;

namespace Atmk.WaterMeter.MIS.Controllers
{
    //[Route("api/[controller]")]
    //[ApiController]
    [Authorize]
    public class MeterReadingRecordController : ControllerBase
    {
        protected Logger _logger = LogManager.GetCurrentClassLogger();
        private readonly TokenHelper _tokenHelper;
        public MeterReadingRecordController(
       TokenHelper tokenHelper)
        {
            _tokenHelper = tokenHelper;
        }
        [HttpPost("/api/{X-Version}/[controller]/GetReadingRecordById")]
        public IActionResult GetReadingRecordById([FromBody]dynamic obj)
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            if (obj.CtdeviceId == null)
            {
                return Ok(new
                {
                    errcode = 0,
                    msg = $""
                });
            }
            //验证用户信息
            string CtdeviceId = obj.CtdeviceId.ToString();
            //根据用户获取片区编码集合进行匹配
            try
            {
                using (var _context = ContextBuilder.Build())
                {
                    var settlementDay7s = _context.SettlementDay.Where(m => m.CtdeviceId == CtdeviceId).OrderByDescending(m => m.ReadTime).Take(100).ToList();
                    var meterReadingRecord7s = _context.MeterReadingRecord.Where(m => m.CtdeviceId == CtdeviceId).OrderByDescending(m => m.ReadTime).Take(12).ToList();
                    var file = new List<object>();
                    foreach (var item in meterReadingRecord7s)
                    {
                        file.Add(new
                        {
                            date = item.ReadTime.ToString("yyyy-MM-dd HH:mm"),
                            dosage = settlementDay7s.FirstOrDefault(m => m.ReadTime.ToString("yyyyMMdd") == item.ReadTime.ToString("yyyyMMdd"))?.Dosage,
                            voltage = item.Voltage,
                            valvestate = PublicSwitch.ValveType(item.ValveState)
                        });
                    }
                    return Ok(new
                    {
                        errcode = 0,
                        msg = "ok",
                        data = new
                        {
                            //total = total_owners.Count,
                            //pageSize,
                            list = file
                        }
                    });
                }
            }
            catch (Exception e)
            {
                _logger.Error(e.Message);
                return Ok(new
                {
                    errcode = 1,
                    msg = $"获取数据错误,错误:{e.Message}"
                });
            }
        }

    }
}